package com.zzb.springcloud.interfaces.impl;

import com.zzb.springcloud.interfaces.LoadBanlance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @CreateTime 2021/6/30 0030 14:56
 * @Author 不浪小生
 */
@Component
@Slf4j
public class LoadBanlanceImpl implements LoadBanlance {

    private AtomicInteger integer = new AtomicInteger(0);

    @Override
    public ServiceInstance getInstance(List<ServiceInstance> instances) {
        if (CollectionUtils.isEmpty(instances)) {
            return null;
        }
        if (integer.get() >= Integer.MAX_VALUE) {
            integer.set(0);
        }
        int instanceSize = instances.size();
        int current;
        int next;
        do {
            current = integer.get();
            next = current + 1;
        } while (!integer.compareAndSet(current, next));
        int index = next % instanceSize;
        log.info("第" + integer.get() + "次请求的实例地址：" + instances.get(index).getUri());
        return instances.get(index);
    }
}
